package ca.tatham.scheduler.simulate;

import java.util.HashMap;
import java.util.Map;

import ca.tatham.scheduler.Scheduler;
import ca.tatham.scheduler.SchedulerException;
import ca.tatham.scheduler.SimpleTask;

public class SimulatedTask extends SimpleTask {

	private final long m_units;
	private final Map<Integer, Object> m_lockResources = new HashMap<Integer, Object>();
	private final Map<Integer, Object> m_unlockResources = new HashMap<Integer, Object>();

	private final TaskLine m_line;

	public SimulatedTask(String name, int priority, TaskLine line, long units,
			ResourceRequirement[] resourceSchedule) {
		super(name, priority);
		m_units = units;
		m_line = line;
		line.setTask(this);
		setResourceScheudle(resourceSchedule);
	}

	public void doTask() {
		try {
			for (int count = 0; count < m_units; count++) {

				Object toLock = m_lockResources.get(count);
				Object toUnlock = m_unlockResources.get(count);
				if (toLock != null) {
					Scheduler.lock(toLock);
				}
				if (toUnlock != null) {
					Scheduler.unlock(toUnlock);
				}

				m_line.unitProcessed();

				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		} finally {
			super.complete();
		}
	}

	public void setResourceScheudle(ResourceRequirement[] resourceSchedule) {
		if (resourceSchedule != null) {
			for (ResourceRequirement resourceReq : resourceSchedule) {
				m_lockResources.put(resourceReq.getLockTime(), resourceReq
						.getResource());
				m_unlockResources.put(resourceReq.getUnlockTime(), resourceReq
						.getResource());
				addResource(resourceReq.getResource());
			}
		}

	}
}
